{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ fort_username }}@{{ server_ip }}</title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="shortcut icon" href="{% static 'favicon.ico' %}" type="image/x-icon">
    <link rel="icon" href="{% static 'favicon.ico' %}" type="image/x-icon">
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/bootstrap/dist/css/bootstrap.min.css' %}">
    <link href="{% static 'bootstrap-fileinput/css/fileinput.min.css' %}" media="all" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">

    <style>
        @media screen and (max-width: 750px) {
            .main-header {
                display: none;
            }
        }

        #dpi {
            height: 1in;
            width: 1in;
            position: absolute;
            left: -100%;
            top: -100%;

        }
    </style>
</head>
<body>
    <header class="main-header">
        <nav class="navbar navbar-light" style="background-color: #e3f2fd; margin-bottom: 0">
            <a class="navbar-brand">当前使用账号为： {{ fort_username }}@{{ server_ip }} </a>
            <div class="form-inline">
                <button class="btn btn-info my-2 my-sm-0" data-toggle="modal" data-target="#uploadModal" onclick="document.getElementById('upload_info').reset();resetInputfile();" style="width: 100px;margin-top: 8px;margin-left: 20px;">
                    <i class="fa fa-upload"></i>
                    <span class="bigger-110">上传文件</span>
                </button>
                <form enctype="multipart/form-data" style="display: inline; margin-left: 20px;">
                    <div class="form-group" style="width: 30%; min-width: 550px; margin-top: 7px;">
                        <div class="input-group" style="width: 100%;">
                            {% if server_protocol == 'telnet' %}
                                <input type="number" class="form-control" id="download_ftp_number" name="download_ftp_number"
                                   style="width: 28%;" min="1" value="22" placeholder="输入sftp连接端口"
                                   oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')};"/>
                            {% endif %}
                            <input class="form-control" type="search" id="download_file" name="download_file"
                                   placeholder="输入要下载文件的全路径" aria-label="Search" style="width: 52%;"/>
                            <input class="btn btn-outline-success download_file" type="button" value="下载"  style="width: 60px;"/>
                        </div>
                    </div>
                </form>
            </div>
        </nav>
    </header>
    <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">导入文件</h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-horizontal">
                            <form id="upload_info">
                                {% if server_protocol == 'telnet' %}
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">sftp端口</label>
                                    <div class="col-sm-9" style="margin-top: 3px;">
                                        <input class="form-control" type="number" id="upload_port" name="upload_port" value="22" min="1"
                                        oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')};">
                                    </div>
                                </div>
                                {% endif %}
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">传输路径</label>
                                    <div class="col-sm-10">
                                        <div class="radio">
                                            <label>
                                                <input type="radio" name="uploadPathType" id="uploadPathType1" value="default" checked="" style="margin-top: 2px;" onclick="cleanUploadPath()">
                                                根目录
                                            </label>
                                        </div>
                                        <div class="radio">
                                            <label style="width:100%;">
                                                <input type="radio" name="uploadPathType" id="uploadPathType2" value="custom" style="margin-top: 10px;" onclick="$('#upload_path').removeAttr('disabled');">
                                                指定路径
                                                <input class="form-control" type="search" id="upload_path" disabled name="upload_path" placeholder="请输入待上传服务器的接收路径，例如/home" style="display: inline; max-width:80%;">
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">是否覆盖同名文件</label>
                                    <div class="col-sm-10" style="margin-top: 5px;">
                                        <div class="radio-inline">
                                            <label style="font-weight: 400;">
                                                <input type="radio" name="uploadPathCheck" id="uploadPathCheck1" value="1" style="margin-top: 2px;" checked="" onclick="cleanUploadPath()">
                                                是
                                            </label>
                                        </div>
                                        <div class="radio-inline">
                                            <label style="font-weight: 400;">
                                                <input type="radio" name="uploadPathCheck" id="uploadPathCheck2" value="0" style="margin-top: 2px;" onclick="$('#upload_path').removeAttr('disabled');">
                                                否
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">上传操作</label>
                                    <div class="col-sm-9">
                                        <div class="input-group" style="width:100%;">
                                            <input type="file" id="upload_file" class="file" name="upload_file" multiple required>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>

    <!-- 用于获取屏幕dpi-->
    <div id='dpi'></div>

    <!-- Display -->
    <div id="display" tabindex="0"></div>

<script src="{% static 'AdminLTE/bower_components/jquery/dist/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static "guacamole/js/all.min.js" %}"></script>
<script src="{% static 'AdminLTE/bower_components/bootstrap/dist/js/bootstrap.min.js' %}"></script>
<script src="{% static 'bootstrap-fileinput/js/fileinput.min.js' %}"></script>
<script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
<!-- Init -->
<script type="text/javascript">

    // Get display div from document
    let display = document.getElementById("display");

    // Instantiate client, using an HTTP tunnel for communications.
    //http://guacamole.apache.org/doc/guacamole-common-js/Guacamole.WebSocketTunnel.html
    let ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
    let ws_path = ws_scheme + '://' + window.location.host + '/ws/webtelnet/{{ fort_user_id }}/{{ group_name }}/';
    let guac = new Guacamole.Client(
        // new Guacamole.HTTPTunnel("tunnel")
        new Guacamole.WebSocketTunnel(ws_path)
    );


    // Add client to display div
    display.appendChild(guac.getDisplay().getElement());

    // Error handler
    guac.onerror = function (error) {
        <!--alert(error);-->
        console.log(error);
    };

    let remote_ip = '{{ remote_ip }}';
    let width = document.documentElement.clientWidth;
    let height = document.documentElement.clientHeight-52;
    //let dpi = getDPI();

    // Connect
    //guac.connect(`${remote_ip},${width},${height},${dpi}`);
    guac.connect(`${remote_ip},${width},${height},0`);

    // Disconnect on close
    window.onunload = function () {
        guac.disconnect();
    };

    // Mouse
    let mouse = new Guacamole.Mouse(guac.getDisplay().getElement());

    mouse.onmousedown =
        mouse.onmouseup =
            mouse.onmousemove = function (mouseState) {
                guac.sendMouseState(mouseState);
            };

    // Keyboard
    //let keyboard = new Guacamole.Keyboard(document);
    let keyboard = new Guacamole.Keyboard(display);
    //解决点击canvas无法获取焦点的问题
    display.addEventListener('click', function () {
        this.focus()
    })

    keyboard.onkeydown = function (keysym) {
        guac.sendKeyEvent(1, keysym);
    };

    keyboard.onkeyup = function (keysym) {
        guac.sendKeyEvent(0, keysym);
    };

    function getDPI() {
        return jQuery('#dpi').height();
    }

    window.onbeforeunload = function (e) {
        return '确定离开此页吗？';
    }

    $("#upload_file").fileinput({
        language: 'zh',
        showUpload: true,
        dropZoneEnabled: false,
        msgPlaceholder: '上传文件...',
        showPreview: false,
        showCaption: true,
        maxFileSize: 10240 * 5,
        maxFileCount: 10,
        uploadUrl: '/fort/terminal_upload_file/{{ fort_user_id }}/',
        mergeAjaxCallbacks: true,
        uploadAsync: false,
        ajaxSettings: {
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            success: function (response) {
                $.alert({
                    title: 'Tips',
                    type: 'green',
                    content: response.msg,
                })
            },
            error: function (response) {
                if(response.statusText=="abort"){
                    resetInputfile()
                    return
                }
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: response.responseJSON.msg,
                })
            },
        },
        browseLabel: '浏览文件',
        removeLabel: '清空',
        uploadLabel: '上传',
        uploadExtraData:function(){//向后台传递参数
            var data={
                {% if server_protocol == 'telnet' %}
                    upload_port:$("#upload_port").val(),
                {% endif %}
                upload_path_type:$("input[name='uploadPathType']:checked").val(),
                upload_path:$("#upload_path").val(),
                upload_path_check:$("input[name='uploadPathCheck']:checked").val()
            };
            return data;
        },
    }).on("filebatchuploadcomplete", function() {
        resetInputfile()
    });

    function resetInputfile(){
        $("#upload_file").fileinput('clear').fileinput('unlock')
        $("#upload_file").parent().siblings('.fileinput-remove').hide()
    }

    $('.download_file').on('click', function () {
        let download_file = $('#download_file').val();
        {% if server_protocol == 'telnet' %}let download_ftp_number=$('#download_ftp_number').val(){% endif %}
        if (download_file.length !== 0) {
            //location.href = '/fort/terminal_download_file/' + {{ fort_user_id }} +'/?download_file=' + download_file {% if server_protocol == 'telnet' %}+ '&download_ftp_number=' = download_ftp_number{% endif %}
            downloadFile('/fort/terminal_download_file/{{ fort_user_id }}/', $.param({
                download_file:download_file,
                {% if server_protocol == 'telnet' %}download_ftp_number:download_ftp_number{% endif %}
            }))
        } else {
            $.alert({
                title: 'Tips',
                type: 'red',
                content: "文件名不能为空！",
            })
        }
    });

    function cleanUploadPath() {
        $('#upload_path').attr('disabled',true);
        $('#upload_path').val('');
    }

    function downloadFile(url, param, filename){
        let xhr = new XMLHttpRequest();
        xhr.open('POST', url+"?"+param);
        xhr.responseType = 'blob';
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
        xhr.onload = function (e,d) {
            if (this.status === 200) {
                let blob = this.response;
                let reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function (e) {
                    let filename = decodeURI(xhr.getResponseHeader("Content-Disposition").replace(/attachment;filename=|"/g, ''))
                    let a = document.createElement('a');
                    a.download = filename;
                    a.href = e.target.result;
                    a.click();
                    $(a).remove();
                }
            } else if(this.status === 500){
                let reader = new FileReader();
                reader.readAsText(xhr.response)
                reader.onload = function(e){
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: JSON.parse(reader.result).msg,
                    })
                }
            }
        };
        xhr.send(param)
    }

</script>
</body>
</html>